import json

from QQLoginTool.QQtool import OAuthQQ
from django.http import JsonResponse
from django.views import View
from django.contrib.auth import login
from apps.oauth.models import OAuthQQUser
from apps.oauth.utils import generic_openid, check_openid
from apps.users.models import User
from meiduo_mail import settings


# Create your views here.
# QQ登录,生成QQLoginTool跳转链接
class QQLoginURLView(View):
    def get(self, request):
        qq = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
            state='xxxxx'
        )
        qq_login_url = qq.get_qq_url()
        return JsonResponse({'code': '0', 'errmsg': 'OK', 'login_url': qq_login_url})


# 获取code
# 请求: 获取code GET /oauth_callback/?code=xxxxx
# 业务逻辑: 通过code获取access_token,再通过access_token获取openid,根据openid判断是否绑定用户,绑定用户则登录,否则跳转到绑定页面
# 响应: 跳转到首页
class OauthQQView(View):
    def get(self, request):
        code = request.GET.get('code')
        if code is None:
            return JsonResponse({'code': '400', 'errmsg': '缺少code'})
        qq = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
            state='xxxxx'
        )
        try:
            access_token = qq.get_access_token(code)
            openid = qq.get_open_id(access_token)
        except:
            return JsonResponse({'code': '400', 'errmsg': '获取openid失败'})
        # 查询openid判断
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 不存在跳转到绑定页面
            access_token = generic_openid(openid)
            response = JsonResponse({'code': '400', 'errmsg': 'openid不存在', 'access_token': access_token})
        else:
            # 存在登录
            # 设置session
            login(request, qquser.user)
            # 设置cookie
            response = JsonResponse({'code': '0', 'errmsg': 'OK'})
            response.set_cookie('username', qquser.user.username)
        return response

    def post(self, request):
        # 1.接收请求
        data = json.loads(request.body.decode())
        # 2.获取请求参数
        mobile = data.get('mobile')
        password = data.get('password')
        sms_code = data.get('sms_code')
        access_token = data.get('access_token')
        openid = check_openid(access_token)
        if openid is None:
            return JsonResponse({'code': '400', 'errmsg': 'openid不存在'})
        # 验证参数(省略)
        # 3.根据手机号进行用户信息的查询
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            # 手机号不存在
            user = User.objects.create_user(username=mobile, mobile=mobile, password=password)
        else:
            # 4.校验密码
            if not user.check_password(password):
                return JsonResponse({'code': '400', 'errmsg': '账号或密码错误'})
        OAuthQQUser.objects.create(user=user, openid=openid)
        login(request, user)
        response = JsonResponse({'code': '0', 'errmsg': 'OK'})
        response.set_cookie('username', user.username)
        return response
